import { getCookie } from 'lj-utils'
import { baseUrl, postReq } from '@/api/request'

export function getRequestBody() {
  return {
    token: getCookie('token') || accountInfo.token,
    os: 'web',
  }
}

export function isLogin() {
  // 这个给大部分页面判断是否已经登录
  return !!getCookie('token')
}

export function cleanToken(){
    console.log('!!!do clean token')
    accountInfo.token = ''
    accountInfo.expiryTime = ''
    document.cookie = 'token' + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
    document.cookie =
      'expiryTime' + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'

    console.log('document token ', getCookie('token'))
}

export async function logout() {
  let token = getCookie('token')
  console.log('logout token ', token)

  const info = await postReq('/logout', {
    token: token,
  })
  console.log('logout result', info)
  switch (info.code) {
    case 0: {
      // 成功登出
      cleanToken()
      break
    }
    case 1: {
      // 参数有误
      break
    }
    case 2: {
      // 登出失败
      break
    }
  }
}

export function login(response) {
  accountInfo.token = response.data[0].token
  accountInfo.expiryTime = response.data[0].expiryTime
  document.cookie = 'token=' + response.data[0].token
  document.cookie = 'expiryTime=' + response.data[0].expiryTime
}

export function checkIsLogin() {
  // 给登录登出管理判断是否登录
  accountInfo.token = getCookieByName('token')
  accountInfo.expiryTime = getCookieByName('expiryTime')
  if (accountInfo.token && accountInfo.expiryTime) {
    if (new Date(accountInfo.expiryTime) > new Date()) {
      return true
    }
  }
  return false
}

// 辅助函数，用于从cookie中读取名为name的cookie的值
function getCookieByName(name) {
  let matches = document.cookie.match(
    new RegExp(
      '(?:^|; )' + name.replace(/([.$?*|{}()[\]\\/+^])/g, '\\$1') + '=([^;]*)'
    )
  )
  return matches ? decodeURIComponent(matches[1]) : undefined
}

export const accountInfo = {
  token: '',
}

export default {
  // 导出函数
  getRequestBody,
  isLogin,
  logout,
  checkIsLogin,
  login,
  accountInfo,
  cleanToken,
}
